// 板块轮动Vue组件
const BoardRotationComponent = {
    template: `
        <div class="board-rotation-page">
            <div class="page-header">
                <h2>板块轮动</h2>
                <div class="header-actions">
                    <el-button type="primary" @click="loadData" :loading="loading">
                        {{ loading ? '加载中...' : '刷新数据' }}
                    </el-button>
                </div>
            </div>

            <!-- 板块轮动表格 -->
            <div class="board-rotation-container">
                <table class="board-rotation-table" v-if="boardDates.length > 0">
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th v-for="date in boardDates.slice(0, 10)" :key="date">
                                {{ formatDate(date) }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(row, index) in 10" :key="index">
                            <td>
                                <span class="rank-label">{{ index + 1 }}</span>
                            </td>
                            <td v-for="date in boardDates.slice(0, 10)" :key="date"
                                :class="getBoardClass(date, index)"
                                @click="selectBoard(getBoardByDateAndRank(date, index))">
                                <div v-if="getBoardByDateAndRank(date, index)">
                                    <div class="board-name">{{ getBoardByDateAndRank(date, index).bkName }}</div>
                                    <div class="zt-num">({{ getBoardByDateAndRank(date, index).ztNum }})</div>
                                </div>
                                <span v-else class="empty">--</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- 无数据提示 -->
                <el-empty v-else description="暂无板块轮动数据" :image-size="200">
                    <el-button type="primary" @click="loadData">刷新数据</el-button>
                </el-empty>
            </div>

            <!-- 个股详情联动表格 -->
            <div v-show="stockDetails.length > 0" class="stock-detail-panel">
                <div class="panel-header">
                    <h3>{{ selectedBoard ? selectedBoard.bkName : '' }} ({{ selectedBoard ? formatDate(selectedBoard.dateTime) : '' }}) - 个股详情</h3>
                    <button class="close-btn" @click="clearStockSelection">×</button>
                </div>
                
                <div v-if="stockLoading" style="text-align: center; padding: 20px;">加载中...</div>
                
                <table v-else class="stock-detail-table">
                    <thead>
                        <tr>
                            <th>股票代码</th>
                            <th>股票名称</th>
                            <th>收盘价</th>
                            <th>涨停时间</th>
                            <th>连板天数</th>
                            <th>封单金额</th>
                            <th>封单量</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="stock in stockDetails" :key="stock.stockCode">
                            <td>{{ stock.stockCode || '--' }}</td>
                            <td>{{ stock.stockName || '--' }}</td>
                            <td>{{ stock.close || '--' }}</td>
                            <td>{{ stock.ztTime || '--' }}</td>
                            <td>{{ stock.lianbanDays || '--' }}</td>
                            <td>{{ formatMoney(stock.fengdanjine) }}</td>
                            <td>{{ formatVolume(stock.fengdanliang) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 统计信息 -->
            <div class="statistics-panel" v-if="boardDates.length > 0">
                <h3>统计信息</h3>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-card class="stat-card">
                            <div class="stat-title">统计日期数</div>
                            <div class="stat-value">{{ boardDates.length }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="8">
                        <el-card class="stat-card">
                            <div class="stat-title">最后更新时间</div>
                            <div class="stat-value">{{ lastUpdateTime }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="8">
                        <el-card class="stat-card">
                            <div class="stat-title">选中板块</div>
                            <div class="stat-value">{{ selectedBoard ? selectedBoard.bkName : '无' }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </div>
    `,
    
    data() {
        return {
            currentUser: '管理员',
            loading: false,
            boardDates: [],
            selectedBoard: null,
            boardDataMap: {},
            lastUpdateTime: new Date().toLocaleString(),
            stockDetails: [],
            stockLoading: false
        }
    },
    
    methods: {
        async loadData() {
            this.loading = true;
            
            try {
                const response = await axios.get('/api/board/rotation');
                console.log('板块轮动数据API响应:', response.data);
                
                // 处理返回的数据
                let boardData = [];
                if (response.data && response.data.data && Array.isArray(response.data.data)) {
                    boardData = response.data.data;
                } else if (Array.isArray(response.data)) {
                    boardData = response.data;
                }
                
                console.log('处理前的板块数据:', boardData);
                this.processBoardData(boardData);
                this.lastUpdateTime = new Date().toLocaleString();
                
            } catch (error) {
                console.error('加载板块轮动数据失败:', error);
            } finally {
                this.loading = false;
            }
        },
        
        processBoardData(data) {
            console.log('开始处理数据...');
            
            // 按日期分组
            const dataByDate = {};
            data.forEach(item => {
                if (!dataByDate[item.dateTime]) {
                    dataByDate[item.dateTime] = [];
                }
                dataByDate[item.dateTime].push(item);
            });
            
            // 对每个日期的板块按涨停数排序
            Object.keys(dataByDate).forEach(date => {
                dataByDate[date].sort((a, b) => (b.ztNum || 0) - (a.ztNum || 0));
            });
            
            this.boardDataMap = dataByDate;
            this.boardDates = Object.keys(dataByDate).sort().reverse();
            
            console.log('处理完成，共', this.boardDates.length, '个日期');
        },
        
        getBoardByDateAndRank(date, rank) {
            if (!this.boardDataMap[date]) return null;
            return this.boardDataMap[date][rank] || null;
        },
        
        getBoardClass(date, rank) {
            const board = this.getBoardByDateAndRank(date, rank);
            if (!board) return '';
            
            const isHighlighted = this.selectedBoard && (
                this.selectedBoard.bkName === board.bkName || 
                this.selectedBoard.bkCode === board.bkCode
            );
            
            return {
                'highlighted': isHighlighted,
                'same-sector': isHighlighted
            };
        },
        
        async selectBoard(board) {
            this.selectedBoard = board;
            if (board && board.bkCode && board.dateTime) {
                await this.loadStockDetails(board.dateTime, board.bkCode);
            }
        },
        
        async loadStockDetails(date, bkCode) {
            this.stockLoading = true;
            try {
                // 确保使用纯数字板块代码（去掉BK前缀）
                const cleanBkCode = bkCode.replace(/^BK/i, '');
                console.log('调用个股详情API，日期:', date, '板块代码:', cleanBkCode);
                
                const response = await axios.get(`/api/board/stocks/${date}/${cleanBkCode}`);
                console.log('个股详情API响应:', response.data);
                
                let stockData = [];
                if (Array.isArray(response.data)) {
                    stockData = response.data;
                } else if (response.data && Array.isArray(response.data.data)) {
                    stockData = response.data.data;
                }
                
                console.log('个股数据数量:', stockData.length);
                this.stockDetails = stockData;
                
            } catch (error) {
                console.error('加载个股详情失败:', error);
                if (window.ElMessage) {
                    window.ElMessage.error('加载个股详情失败');
                }
            } finally {
                this.stockLoading = false;
            }
        },
        
        clearStockSelection() {
            this.selectedBoard = null;
            this.stockDetails = [];
        },
        
        formatMoney(value) {
            if (!value || value === '0' || value === '0.00') return '--';
            const num = parseFloat(value);
            if (num >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (num >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toFixed(2);
        },
        
        formatVolume(value) {
            if (!value || value === '0' || value === '0.00') return '--';
            const num = parseFloat(value);
            if (num >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (num >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toFixed(0);
        },
        
        formatDate(dateStr) {
            if (!dateStr || dateStr.length !== 8) return dateStr;
            return `${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
        }
    },
    
    mounted() {
        console.log('板块轮动组件启动');
        this.loadData();
    }
};